package net.wanho.shop.controller;

import lombok.RequiredArgsConstructor;
import net.wanho.shop.entity.SysFile;
import net.wanho.shop.service.FileService;
import net.wanho.shop.vo.Page;
import net.wanho.shop.vo.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2025-09-19 16:25
 * Description：<描述>
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final FileService fileService;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param sysFile
     * @return
     */
    @GetMapping("/page")
    public R findByPage(@RequestParam(defaultValue = "1") int pageNum,
                        @RequestParam(defaultValue = "10") int pageSize,
                        SysFile sysFile){
        Page<SysFile> page = fileService.findByPage(pageNum, pageSize, sysFile);
        return R.success(page);
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String url = fileService.upload(file);
        return url;
    }

    /**
     * 文件下载
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        byte[] bytes = fileService.getFile(fileUUID);

        response.setContentType("application/octet-stream"); // 二进制流
        response.setHeader("Content-Disposition", "attachment;filename=" + fileUUID);

        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.close();
    }

}
